package edu.tts.dao;

import java.sql.SQLException;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import edu.DBUtil.JdbcTemplate;
import edu.tts.domain.Train;

public class QueryDao {
	public List<Train> queryTrain(Train train){
		 String sql="select * from tts_trainInfo " + 
				 	        "where fromAddress=? and toaddress=?";
				 	    if(train.getTrainId().length()!=0) {
				 	        sql+=" and trainId=?";
				 	    }
				 	    if(null!=train.getDate()) {
				 	        sql+=" and startdate=to_date(?,'yyyy-mm-dd')";
				 	    }
				 	    List<Object> params=new ArrayList<>();
				 	    params.add(train.getFromAddress());
				 	    params.add(train.getToAddress());
				 	
				 	    if(train.getTrainId().length()!=0) {
				 	        params.add(train.getTrainId());
				 	    }
				 	    if(null!=train.getDate()) {
				 	        DateTimeFormatter dft=DateTimeFormatter.ofPattern("yyyy/MM/dd");
				 	        params.add(dft.format(train.getDate()));
				 	    }		
				 	
				 	    List<Train> list=JdbcTemplate.query(sql, (rs)->{
				 	        List<Train> list0=new ArrayList<>();
				 	        try {
				 	            while(rs.next()) {
				 	                Train train0=new Train(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getDate(5).toLocalDate(),rs.getTime(6).toLocalTime(),rs.getBigDecimal(7));
				 	                list0.add(train0);
				 	            }
				 	        } catch (SQLException e) {
				 	            e.printStackTrace();
				 	        }
				 	        return list0;
				 	    }, params.toArray());
				 	    return list;

	}
}

